import os
import subprocess

from WebBackend.store.ConfigurationStore import ConfigurationStore
from WebBackend.store.UserStore import UserStore


class DirectoryStore:
    def __init__(self, config_store: ConfigurationStore, user_store: UserStore):
        self.configStore = config_store
        self.userStore = user_store
        self.dirs = []
        self.reload_store()
        self.update_size()

    def reload_store(self):
        if lu := self.configStore.get_data_by_key('local_root'):
            self.dirs.append({
                'type': 'local',
                'owner': 'local',
                'path': lu,
                'enabled': True,
            })
        if lu := self.configStore.get_data_by_key('local_enable', lower=True):
            if lu == 'yes':
                for item in self.userStore.local_users:
                    self.dirs.append({
                        'type': 'local',
                        'owner': item.get('username'),
                        'path': item.get('home'),
                        'enabled': True,
                    })
        ####################################
        if au := self.configStore.get_data_by_key('anon_root'):
            self.dirs.append({
                'key': 'anon_root',
                'path': au,
                'enabled': True,
            })
        ####################################
        if vu := self.configStore.get_data_by_key('vu_root'):
            pass

    def update_size(self):
        for d in self.dirs:
            # 获取目录大小（GB）
            if os.path.exists(d['path']):
                try:
                    size = subprocess.check_output(["du", "-sb", d.get('path')]).split()[0].decode()
                    size_gb = int(size) / (1024 ** 3)

                    # 获取文件数量
                    files = int(
                        subprocess.check_output(["find", d.get('path'), "-type", "f", "-printf", "%C+\\n"]).count(
                            b'\n'))
                    d['size'] = size_gb
                except any as e:
                    d['size'] = 0
            else:
                d['size'] = 0
